package com.mall.controller;

import com.mall.db.service.FileService;
import com.wxd.utils.FileUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping("/file/fc")
public class FileController {

    @Value("${file.root.photo}")
    private String root;

    @Resource(name = "fileService")
    private FileService fs;

    @RequestMapping("/fileUpload")
    @ResponseBody
    public Map<String,Object> fileUpload(MultipartFile file){

        Map<String,Object> map = new HashMap<>();
        try {

            if (file != null) {
                String fileName = file.getOriginalFilename();

                String suffix = fileName.substring(fileName.lastIndexOf("."));
                String newFileName = System.currentTimeMillis() + "" + suffix;
                File f1 = new File(root, newFileName);
                FileUtil.createDir(f1);
                File f2 = new File(root, newFileName);
                FileUtil.createDir(f2);
                file.transferTo(f2);

                com.mall.db.domain.File f = new com.mall.db.domain.File();
                f.setFileSize(file.getSize());
                f.setOldFilename(fileName);
                f.setNewFilename(newFileName);
                f.setSuffix(suffix);
                f.setPath(f2.getAbsolutePath());

                //执行新增
                boolean b = fs.save(f);
                if (b){
                    map.put("file",f);
                    map.put("is",true);
                }else {
                    map.put("file","");
                    map.put("is",false);
                }

            }
        }catch (IOException e){
            map.put("file","");
            map.put("is",false);

            e.printStackTrace();
        }

        return map;

    }

    @RequestMapping("/showImg/{id}")
    public void showImg(@PathVariable(name = "id") int id, HttpServletResponse res){
        try {
            com.mall.db.domain.File f = fs.getById(id);
            File f2 = new File(f.getPath());
            FileInputStream fis = new FileInputStream(f2);
            OutputStream fos = res.getOutputStream();
            byte bs[] = new byte[1024];
            int i = 0;
            while ((i = fis.read(bs))>0) {
                fos.write(bs,0,i);

            }
            fos.close();
            fis.close();
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
